package com.lanyou.cook.camel.service;

import java.io.IOException;
import java.util.concurrent.Executor;



import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;

import com.lanyou.cook.camel.commons.Constants;

/**
 * 用于选举出作为调度器的节点
 * @author ly-lihailang
 *
 */
public class LeaderElectionService {

	private CuratorService curatorService;
	
	private LeaderLatch leaderLatch;
	
	/**
	 * 初始化创建LeaderLatch实例，并启动
	 * @throws Exception
	 */
	public void init() throws Exception {
		leaderLatch = new LeaderLatch(curatorService.getClient(), Constants.ZOOKEPPER_PATH_JOB_SCHEDULER_LEADER);
		leaderLatch.start();
	}
	
	/**
	 * 销毁实例前将LeaderLatch实例关闭
	 */
	public void close(){
		closeLeaderLatch();
	}
	
	/**
	 * 关闭LeaderLatch实例关闭
	 */
	private void closeLeaderLatch(){
		if(leaderLatch != null){
			try {
				leaderLatch.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			leaderLatch = null;
		}
	}
	
	/**
	 * 判断是否leader
	 * @return 如果是则返回true，不是则为false
	 */
	public boolean isLeader() {
		return leaderLatch.hasLeadership();
	}
	
	/**
	 * 往leaderLatch中添加监听
	 * @param listener 监听实例
	 */
	public void addListener(LeaderLatchListener listener){
		leaderLatch.addListener(listener);
	}
	
	public void addListener(LeaderLatchListener listener, Executor executor){
		leaderLatch.addListener(listener, executor);
	}
	
	/**
	 * 将监听移除
	 * @param listener
	 */
	public void removeListener(LeaderLatchListener listener){
		leaderLatch.removeListener(listener);
	}

	public CuratorService getCuratorService() {
		return curatorService;
	}

	public void setCuratorService(CuratorService curatorService) {
		this.curatorService = curatorService;
	}
	public static void main(String[] args) {
		try {
			CuratorService curatorService = new CuratorService();
			curatorService.init();
			LeaderElectionService leaderElectionService = new LeaderElectionService();
			leaderElectionService.setCuratorService(curatorService);
			leaderElectionService.init();
			System.out.println(leaderElectionService.isLeader());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
